package com.vrv.netmgr.assets.chart;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.UrlPrefix;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.netmgr.R;

/**
 * 资产信息概况
 *
 * @author gaopei
 *
 */
@SuppressLint("HandlerLeak")
public class AssetsChartActivity extends Activity {

    /** 为统计图开辟的区域 */
    private LinearLayout layout;
    List<String> listLabel = new ArrayList<String>();
    List<Object> listVal = new ArrayList<Object>();
    /** 饼形图 */
    GraphicalView pieChartView = null;
    CategorySeries dataset;
    DefaultRenderer renderer;
    /**
     * 等待对话框
     */
    private ProgressDialog progressDialog;
    /**
     * 查询
     */
    private static final int QUERY_ANTIVIRUS = 1;
    private static final int QUERY_USED_IP = 2;
    private static final int QUERY_LOCAL_LEAK = 3;
    private static final int QUERY_REGISTER_RATE = 4;
    private static final int NET_ERR = 99;
    private String chartTitle;

    // PopWindow检索条件相关
    private ImageButton moreFuncBtn;
    private PopupWindow pwMyPopWindow;
    private ListView lvPopupList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.alarm_region_statistics_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tools_title);
        initView();
        progressDialog = ProgressDialog.show(AssetsChartActivity.this, "", "查询中...", true, true);

        new Thread(new Runnable() {
            @Override
            public void run() {
                getDataFromServer(QUERY_ANTIVIRUS);
                Message msg = new Message();
                msg.arg1 = QUERY_ANTIVIRUS;
                msg.arg2 = 1;
                handler.sendMessage(msg);
            }
        }).start();
    }

    /**
     * 处理器
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            progressDialog.dismiss();

            int what = msg.arg1;
            boolean showVal = msg.arg2 == 0 ? Boolean.FALSE : Boolean.TRUE;
            switch (what) {
            case QUERY_ANTIVIRUS:
                buildPieChartView(showVal);
                break;
            case QUERY_REGISTER_RATE:
                buildLineChartView();
                break;
            case NET_ERR:
                Toast.makeText(AssetsChartActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
                break;
            }
        }
    };

    private void initView() {
        TextView title = (TextView) findViewById(R.id.title_text);
        title.setText("资产信息概况");
        // 返回按钮
        ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
        backBtn.setVisibility(View.VISIBLE);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        // 初始化chart的渲染位置
        layout = (LinearLayout) findViewById(R.id.bar_chart);
        iniPopupWindow();
        // 更多操作按钮
        moreFuncBtn = (ImageButton) findViewById(R.id.moreFunctionBtn);
        moreFuncBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pwMyPopWindow.isShowing()) {
                    pwMyPopWindow.dismiss();// 关闭
                } else {
                    pwMyPopWindow.showAsDropDown(moreFuncBtn);// 显示
                }
            }
        });
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void iniPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.title_func_popupwindow, null);
        lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
        pwMyPopWindow = new PopupWindow(layout);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件

        String[] arr = getResources().getStringArray(R.array.assetsChartType);
        if (null == itemDatas) {
            itemDatas = new ArrayList();
        } else {
            itemDatas.clear();
        }
        for (int i = 0; i < arr.length; i++) {
            PopItem item = new PopItem();
            item.title = arr[i];
            item.check = false;
            if (0 == i) {
                item.check = true;
            }
            itemDatas.add(item);
        }
        if (null == pAdapter) {
            pAdapter = new PopWindowAdapter(itemDatas, AssetsChartActivity.this);
        }
        lvPopupList.setAdapter(pAdapter);
        lvPopupList.setOnItemClickListener(new ClickPopupItemListener());

        // 控制popupwindow的宽度和高度自适应
        lvPopupList.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
        pwMyPopWindow.setHeight(LayoutParams.WRAP_CONTENT);

        // 控制popupwindow点击屏幕其他地方消失
        pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg_popupwindow));
        // 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
        pwMyPopWindow.setOutsideTouchable(true);
    }

    private class ClickPopupItemListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
            pwMyPopWindow.dismiss();
            progressDialog = ProgressDialog.show(AssetsChartActivity.this, "", "查询中...", true, true);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int temp = 0;
                    int what = 0;
                    int showVal = 1;

                    switch (position) {
                    case QUERY_ANTIVIRUS - 1:
                        temp = QUERY_ANTIVIRUS;
                        what = QUERY_ANTIVIRUS;
                        break;
                    case QUERY_USED_IP - 1:
                        temp = QUERY_USED_IP;
                        what = QUERY_ANTIVIRUS;

                        break;
                    case QUERY_LOCAL_LEAK - 1:
                        temp = QUERY_LOCAL_LEAK;
                        what = QUERY_ANTIVIRUS;
                        showVal = 0;
                        break;
                    case QUERY_REGISTER_RATE - 1:
                        temp = QUERY_REGISTER_RATE;
                        what = QUERY_REGISTER_RATE;
                        break;
                    }
                    getDataFromServer(temp);

                    Message msg = new Message();
                    msg.arg1 = what;
                    msg.arg2 = showVal;
                    handler.sendMessage(msg);
                }
            }).start();

            for (int i = 0; i < itemDatas.size(); i++) {
                if (position == i) {
                    itemDatas.get(i).check = true;
                } else {
                    itemDatas.get(i).check = false;
                }
            }
            pAdapter.notifyDataSetChanged();
            // Toast.makeText(AssetsChartActivity.this, "" +
            // itemDatas.get(position).title, Toast.LENGTH_LONG).show();
        }
    }

    public List<PopItem> itemDatas;
    public PopWindowAdapter pAdapter;

    public class PopWindowAdapter extends BaseAdapter {
        public List<PopItem> lst;
        public Context mContext;

        public PopWindowAdapter(List<PopItem> lst, Context context) {
            this.lst = lst;
            this.mContext = context;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return lst.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return lst.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(AssetsChartActivity.this).inflate(R.layout.list_item_popupwindow, null);
            }
            CheckBox cBox = (CheckBox) convertView.findViewById(R.id.check);
            TextView title = (TextView) convertView.findViewById(R.id.tv_list_item);

            cBox.setChecked(lst.get(position).check);
            title.setText(lst.get(position).title);

            return convertView;
        }

    }

    public class PopItem {
        public String title;
        public boolean check = false;
    }

    @SuppressLint("SimpleDateFormat")
    public void buildLineChartView() {
        if (null == listLabel || listLabel.size() == 0) {
            return;
        }
        if (null == listVal || listVal.size() == 0) {
            return;
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String[] titles = new String[] { "注册率" };
        List<Date[]> dates = new ArrayList<Date[]>();
        List<Object[]> values = new ArrayList<Object[]>();
        int length = titles.length;
        for (int i = 0; i < length; i++) {
            dates.add(new Date[5]);
            try {
                for (int j = 0; j < 5; j++)
                    dates.get(i)[j] = formatter.parse(listLabel.get(j));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        values.add(listVal.toArray());
        length = values.get(0).length;
        int[] colors = new int[] { Color.BLUE };
        PointStyle[] styles = new PointStyle[] { PointStyle.POINT };
        XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
        setChartSettings(renderer, chartTitle, "日期", "", dates.get(0)[0].getTime(), dates.get(0)[4].getTime(), 0, 100, Color.BLACK, Color.BLACK);
        renderer.setXLabels(5);
        renderer.setYLabels(6);
        renderer.setShowGrid(true);
        renderer.setXLabelsColor(Color.BLACK);
        renderer.setYLabelsColor(0, Color.BLACK);
        renderer.setXLabelsAngle(-20);
        renderer.setXLabelsPadding(10);
        renderer.setMarginsColor(getResources().getColor(R.color.gray1));
        length = renderer.getSeriesRendererCount();
        for (int i = 0; i < length; i++) {
            SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
            seriesRenderer.setDisplayChartValues(true);
        }
        if (pieChartView != null)
            layout.removeView(pieChartView);
        pieChartView = ChartFactory.getTimeChartView(this, buildDateDataset(titles, dates, values), renderer, "yyyy/MM/dd");
        layout.addView(pieChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    }

    /**
     * Builds an XY multiple time dataset using the provided values.
     *
     * @param titles
     *            the series titles
     * @param xValues
     *            the values for the X axis
     * @param yValues
     *            the values for the Y axis
     * @return the XY multiple time dataset
     */
    protected XYMultipleSeriesDataset buildDateDataset(String[] titles, List<Date[]> xValues, List<Object[]> yValues) {
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        int length = titles.length;
        for (int i = 0; i < length; i++) {
            TimeSeries series = new TimeSeries(titles[i]);
            Date[] xV = xValues.get(i);
            Object[] yV = yValues.get(i);
            int seriesLength = xV.length;
            for (int k = 0; k < seriesLength; k++) {
                series.add(xV[k], Double.valueOf(yV[k].toString()).doubleValue());
            }
            dataset.addSeries(series);
        }
        return dataset;
    }

    /**
     * Sets a few of the series renderer settings.
     *
     * @param renderer
     *            the renderer to set the properties to
     * @param title
     *            the chart title
     * @param xTitle
     *            the title for the X axis
     * @param yTitle
     *            the title for the Y axis
     * @param xMin
     *            the minimum value on the X axis
     * @param xMax
     *            the maximum value on the X axis
     * @param yMin
     *            the minimum value on the Y axis
     * @param yMax
     *            the maximum value on the Y axis
     * @param axesColor
     *            the axes color
     * @param labelsColor
     *            the labels color
     */
    protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle, String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor, int labelsColor) {
        renderer.setChartTitle(title);
        renderer.setXTitle(xTitle);
        renderer.setYTitle(yTitle);
        renderer.setXAxisMin(xMin);
        renderer.setXAxisMax(xMax);
        renderer.setYAxisMin(yMin);
        renderer.setYAxisMax(yMax);
        renderer.setAxesColor(axesColor);
        renderer.setLabelsColor(labelsColor);
    }

    /**
     * Builds an XY multiple series renderer.
     *
     * @param colors
     *            the series rendering colors
     * @param styles
     *            the series point styles
     * @return the XY multiple series renderers
     */
    protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
        XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
        setRenderer(renderer, colors, styles);
        return renderer;
    }

    protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) {
        renderer.setAxisTitleTextSize(20);
        renderer.setChartTitleTextSize(25);
        renderer.setLabelsTextSize(20);
        renderer.setLegendTextSize(20);
        renderer.setPointSize(15f);
        renderer.setMargins(new int[] { 40, 20, 45, 20 });
        int length = colors.length;
        for (int i = 0; i < length; i++) {
            XYSeriesRenderer r = new XYSeriesRenderer();
            r.setColor(colors[i]);
            r.setPointStyle(styles[i]);
            renderer.addSeriesRenderer(r);
        }
    }

    public void buildPieChartView(boolean showVal) {
        /** 统计图所需数据 */
        int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.YELLOW, Color.RED, getResources().getColor(R.color.darkblue), getResources().getColor(R.color.brown),
                getResources().getColor(R.color.orange), getResources().getColor(R.color.purple), getResources().getColor(R.color.darkorchid) };
        Object[] labels = listLabel.toArray();
        Object[] vals = listVal.toArray();// new long[] { 0L, 349L, 0L, 116L,
                                          // 135L, 8L, 0L };
        renderer = buildCategoryRenderer(colors);
        renderer.setZoomButtonsVisible(false);
        renderer.setZoomEnabled(true);
        renderer.setChartTitle(chartTitle);
        renderer.setChartTitleTextSize(25);
        renderer.setDisplayValues(showVal);
        renderer.setLabelsColor(Color.BLACK);
        renderer.setShowLabels(true);
        renderer.setClickEnabled(true);
        dataset = buildCategoryDataset("", labels, vals);
        if (pieChartView != null)
            layout.removeView(pieChartView);
        pieChartView = ChartFactory.getPieChartView(this, dataset, renderer);
        layout.addView(pieChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        pieChartView.setOnClickListener(new MyClickListener());
    }

    private class MyClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            SeriesSelection seriesSelection = pieChartView.getCurrentSeriesAndPoint();
            if (seriesSelection != null) {
                for (int i = 0; i < dataset.getItemCount(); i++) {
                    renderer.getSeriesRendererAt(i).setHighlighted(i == seriesSelection.getPointIndex());
                }
                pieChartView.repaint();
                // Toast.makeText(
                // AssetsChartActivity.this,
                // "Chart data point index "
                // + seriesSelection.getPointIndex() + " selected"
                // + " point value=" + seriesSelection.getValue(),
                // Toast.LENGTH_SHORT).show();
            }
        }

    }

    public CategorySeries buildCategoryDataset(String title, Object[] labels, Object[] values) {
        CategorySeries series = new CategorySeries(title);
        int k = 0;
        for (Object value : values) {
            series.add((String) labels[k++], (Long) value);
        }
        return series;
    }

    public DefaultRenderer buildCategoryRenderer(int[] colors) {
        DefaultRenderer renderer = new DefaultRenderer();
        renderer.setLabelsTextSize(20);
        renderer.setLegendTextSize(20);
        renderer.setShowLegend(false);
        renderer.setMargins(new int[] { 0, 30, 15, 0 });
        for (int i = 0; i < listLabel.size(); i++) {
            SimpleSeriesRenderer r = new SimpleSeriesRenderer();
            r.setColor(colors[i]);
            renderer.addSeriesRenderer(r);
        }
        return renderer;
    }

    // 查询所有数据
    public void getDataFromServer(int statisticsType) {
        switch (statisticsType) {
        case QUERY_ANTIVIRUS:
            chartTitle = "杀毒软件安装情况";
            break;
        case QUERY_USED_IP:
            chartTitle = "设备IP占用情况";
            break;
        case QUERY_LOCAL_LEAK:
            chartTitle = "本地漏洞统计";
            break;
        case QUERY_REGISTER_RATE:
            chartTitle = "最近5天内注册率变化曲线";
            break;
        }
        Map<String, String> map = new HashMap<String, String>();
        boolean retVal = qryRegisterStat(map, statisticsType);
        if (!retVal)
            handler.sendEmptyMessage(NET_ERR);
    }

    public boolean qryRegisterStat(Map<String, String> map, int statisticsType) {
        boolean retVal = false;
        HttpClientToServer httpClientToServer = new HttpClientToServer();
        String urlPrefix = new UrlPrefix(getApplicationContext()).getUrlPrefix();
        String urlTailString = null;
        switch (statisticsType) {
        case QUERY_ANTIVIRUS:
            urlTailString = "/deviceInfo/getKvsInstallInfo.do";
            break;
        case QUERY_USED_IP:
            urlTailString = "/deviceInfo/getIpUseageInfo.do";
            break;
        case QUERY_LOCAL_LEAK:
            urlTailString = "/deviceInfo/getPatchInfo.do";
            break;
        case QUERY_REGISTER_RATE:
            urlTailString = "/deviceInfo/getLatestEnrollment.do";
            break;
        }
        String urlAddr = urlPrefix + urlTailString;
        String response = httpClientToServer.doPost(urlAddr, map);
        if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response))
            return retVal;
        try {
            JSONTokener jsonParser = new JSONTokener(response);
            JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
            retVal = jsonObj.getBoolean("success");
            if (!retVal)
                return retVal;
            int count = jsonObj.getInt("totalRecords");
            if (count < 1)
                return retVal;
            JSONArray jArr = jsonObj.getJSONArray("records");
            listLabel.clear();
            listVal.clear();
            for (int i = jArr.length() - 1; i >= 0; i--) {
                JSONObject jObj = (JSONObject) jArr.opt(i);
                getFieldsVal(jObj, statisticsType);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return retVal;
    }

    public void getFieldsVal(JSONObject jObj, int statisticsType) {
        try {
            switch (statisticsType) {
            case QUERY_ANTIVIRUS:
                long kvsPersent = jObj.getLong("kvsPersent");
                long unKvsPersent = jObj.getLong("unKvsPersent");
                long totalKVSNum = kvsPersent + unKvsPersent;

                if (totalKVSNum == 0) {
                    kvsPersent = 1;
                    unKvsPersent = 1;
                    totalKVSNum = kvsPersent + unKvsPersent;
                }

                listLabel.add("已安装:" + kvsPersent + " , " + new BigDecimal(kvsPersent * 1.00 / totalKVSNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                listLabel.add("未安装:" + unKvsPersent + " , " + new BigDecimal(unKvsPersent * 1.00 / totalKVSNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                
                listVal.add(kvsPersent);
                listVal.add(unKvsPersent);
                break;
            case QUERY_USED_IP:
                long idleNum = jObj.getLong("idle");
                long registeredNum = jObj.getLong("registered");
                long unRegisteredNum = jObj.getLong("unRegistered");
                long totalNum = idleNum + registeredNum + unRegisteredNum;

                if (totalNum == 0) {
                    idleNum = 1;
                    registeredNum = 1;
                    unRegisteredNum = 1;
                    totalNum = idleNum + registeredNum + unRegisteredNum;
                }

                listLabel.add("空闲IP:" + idleNum + " , " + new BigDecimal((idleNum * 1.00 / totalNum) * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                listLabel.add("已注册计算机IP:" + registeredNum + " , " + new BigDecimal((registeredNum * 1.00 / totalNum) * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                listLabel.add("未注册智能终端IP:" + unRegisteredNum + " , " + new BigDecimal((unRegisteredNum * 1.00 / totalNum) * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");

                listVal.add(idleNum);
                listVal.add(registeredNum);
                listVal.add(unRegisteredNum);
                break;
            case QUERY_LOCAL_LEAK:
                long MRisk = jObj.getLong("MRisk");
                long LRisk = jObj.getLong("LRisk");
                long HRisk = jObj.getLong("HRisk");
                long totalCountRisk = MRisk + LRisk + HRisk;

                if (totalCountRisk <= 0) {
                    MRisk = 1;
                    LRisk = 1;
                    HRisk = 1;
                    totalCountRisk = MRisk + LRisk + HRisk;
                }

                listLabel.add("中风险:" + MRisk + " , " + new BigDecimal((MRisk * 1.00 / totalCountRisk) * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                listLabel.add("低风险:" + LRisk + " , " + new BigDecimal((LRisk * 1.00 / totalCountRisk) * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");
                listLabel.add("高风险:" + HRisk + " , " + new BigDecimal((HRisk * 1.00 / totalCountRisk) * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");

                listVal.add(MRisk);
                listVal.add(LRisk);
                listVal.add(HRisk);

                break;
            case QUERY_REGISTER_RATE:
                // Iterator<?> iter = jObj.keys();
                // String pastDate = iter.next().toString();
                String date = jObj.getString("date");
                Double rate = jObj.getDouble("rate");

                listLabel.add(date);
                listVal.add(rate);
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }
}
